<?php

class Auth extends Zend_Auth implements ISingleton
{
    /**
     * @var Auth
     */
    protected static $_instance = null;

    /**
     * Current authenticate profile row.
     *
     * @var UserRow
     */
    protected $_currentProfile;

    /**
     * @return Auth
     */
    protected function __construct() {}

    /**
     * Returns an instance of Auth
     * Singleton pattern implementation
     *
     * @return Auth Provides a fluent interface
     */
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     * Return current loginned Profile object
     *
     * @return UserRow
     * @throws Zend_Auth_Exception
     */
    public function getProfile()
    {
    	if ($this->_currentProfile instanceof UserRow) {
    		return $this->_currentProfile;
    	}

    	// Get identity from session
    	$identity = $this->getIdentity();
    	if (!$identity) {
    		return null;
    	}
		
    	$currentProfile = UserPeer::getInstance()->find($identity)->current();
    	if (!$currentProfile) {
    		$this->clearIdentity();
    		throw new Zend_Auth_Exception('User not found');
    	}

    	$this->_currentProfile = $currentProfile;
    	return $this->_currentProfile;
    }

    /**
     * Clear identity and cookie.
     *
     * @return void
     */
    public function onLogout()
    {
    	$this->clearIdentity();
    }
}